document.addEventListener('DOMContentLoaded', function() {
  // Check if user is authenticated
  if (ApiService.redirectIfNotAuthenticated()) {
    return;
  }
  
  // Initialize components
  const topNavBar = new TopNavBar();
  topNavBar.init();
  
  const sideBar = new SideBar();
  sideBar.init('financial');
  
  // Get URL parameters
  const urlParams = new URLSearchParams(window.location.search);
  const productId = urlParams.get('id');
  const amount = parseFloat(urlParams.get('amount') || 0);
  
  if (!productId) {
    showError('产品ID不能为空');
    return;
  }
  
  if (!amount || amount <= 0) {
    showError('购买金额不正确');
    return;
  }
  
  // Variables
  let productDetail = null;
  let expectedProfit = 0;
  let totalAmount = 0;
  
  // Load product details
  loadProductDetail(productId, amount);
  
  /**
   * Load product detail
   */
  function loadProductDetail(id, purchaseAmount) {
    ApiService.get(`/api/finance/product/${id}`)
      .then(response => {
        if (response.code === 0 && response.data) {
          productDetail = response.data;
          
          // Check if product is available for purchase
          if (productDetail.status !== 1) {
            showError('该产品当前不可购买');
            return;
          }
          
          // Validate amount
          if (purchaseAmount < productDetail.minAmount) {
            showError(`购买金额不能低于¥${productDetail.minAmount}`);
            return;
          }
          
          if (productDetail.maxAmount && purchaseAmount > productDetail.maxAmount) {
            showError(`购买金额不能高于¥${Utils.formatNumber(productDetail.maxAmount)}`);
            return;
          }
          
          // Calculate expected profit
          expectedProfit = (purchaseAmount * productDetail.expectedReturn * productDetail.duration) / (100 * 365);
          totalAmount = purchaseAmount + expectedProfit;
          
          // Render purchase form
          renderPurchaseForm(productDetail, purchaseAmount, expectedProfit, totalAmount);
        } else {
          showError(response.message || '获取产品详情失败');
        }
      })
      .catch(error => {
        console.error('Error loading product detail:', error);
        showError('获取产品详情失败');
      });
  }
  
  /**
   * Render purchase form
   */
  function renderPurchaseForm(product, purchaseAmount, profit, total) {
    const containerElement = document.getElementById('purchase-content');
    
    // Parse dates
    const valueDate = new Date(product.valueDate);
    const dueDate = new Date(product.dueDate);
    
    // Build HTML
    let html = `
      <div class="purchase-header">
        <div class="purchase-step">
          <div class="step-item completed">
            <div class="step-number">1</div>
            <div class="step-text">选择产品</div>
          </div>
          <div class="step-arrow">
            <i class="fas fa-chevron-right"></i>
          </div>
          <div class="step-item active">
            <div class="step-number">2</div>
            <div class="step-text">确认信息</div>
          </div>
          <div class="step-arrow">
            <i class="fas fa-chevron-right"></i>
          </div>
          <div class="step-item">
            <div class="step-number">3</div>
            <div class="step-text">完成购买</div>
          </div>
        </div>
      </div>
      
      <div class="product-summary">
        <div class="summary-header">
          <div class="product-icon">
            <i class="fas fa-chart-line"></i>
          </div>
          <div class="product-title">
            <div class="product-name">${product.productName}</div>
            <div class="product-code">${product.productCode}</div>
          </div>
        </div>
        
        <div class="summary-details">
          <div class="summary-detail">
            <div class="detail-label">预期年化收益率</div>
            <div class="detail-value accent">${product.expectedReturn}%</div>
          </div>
          <div class="summary-detail">
            <div class="detail-label">投资期限</div>
            <div class="detail-value">${product.duration}天</div>
          </div>
          <div class="summary-detail">
            <div class="detail-label">起息日</div>
            <div class="detail-value">${Utils.formatDate(valueDate)}</div>
          </div>
          <div class="summary-detail">
            <div class="detail-label">到期日</div>
            <div class="detail-value">${Utils.formatDate(dueDate)}</div>
          </div>
          <div class="summary-detail">
            <div class="detail-label">风险等级</div>
            <div class="detail-value">${getRiskText(product.riskLevel)}</div>
          </div>
          <div class="summary-detail">
            <div class="detail-label">投资类型</div>
            <div class="detail-value">固定收益</div>
          </div>
        </div>
      </div>
      
      <div class="purchase-form">
        <div class="card amount-card">
          <div class="card-header">
            <h3 class="card-title">投资信息</h3>
          </div>
          <div class="card-body">
            <div class="amount-display">
              <div class="amount-label">投资金额</div>
              <div class="amount-value">¥${Utils.formatNumber(purchaseAmount)}</div>
            </div>
            
            <div class="profit-estimate">
              <div class="profit-label">预期收益</div>
              <div class="profit-value">¥${profit.toFixed(2)}</div>
              <div class="profit-hint">
                收益计算公式：投资金额 × 预期年化收益率 × 投资天数 ÷ 365
              </div>
            </div>
            
            <div class="form-group">
              <label for="payment-password">交易密码</label>
              <div class="input-wrapper">
                <input type="password" id="payment-password" placeholder="请输入交易密码" class="form-control">
                <div class="input-icon">
                  <i class="fas fa-lock"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="agreement-section">
          <div class="agreement-check">
            <input type="checkbox" id="agreement-check">
            <label for="agreement-check">
              我已阅读并同意<span class="agreement-links"><a href="javascript:void(0)" id="agreement-link">《理财产品协议》</a></span>，了解并接受产品风险
            </label>
          </div>
        </div>
        
        <button class="btn btn-primary btn-block" id="confirm-btn">确认购买</button>
      </div>
    `;
    
    containerElement.innerHTML = html;
    
    // Add event listeners
    document.getElementById('agreement-link').addEventListener('click', function() {
      showAgreement(product);
    });
    
    document.getElementById('confirm-btn').addEventListener('click', function() {
      confirmPurchase(product, purchaseAmount);
    });
  }
  
  /**
   * Show agreement modal
   */
  function showAgreement(product) {
    // Create modal element
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.id = 'agreement-modal';
    
    modal.innerHTML = `
      <div class="modal-content">
        <div class="modal-header">
          <h3>理财产品协议</h3>
          <span class="modal-close">&times;</span>
        </div>
        <div class="modal-body">
          <div class="agreement-content">
            <h4>产品说明</h4>
            <p>产品名称：${product.productName}</p>
            <p>产品代码：${product.productCode}</p>
            <p>预期年化收益率：${product.expectedReturn}%</p>
            <p>投资期限：${product.duration}天</p>
            <p>起息日：${Utils.formatDate(new Date(product.valueDate))}</p>
            <p>到期日：${Utils.formatDate(new Date(product.dueDate))}</p>
            <p>风险等级：${getRiskText(product.riskLevel)}</p>
            
            <h4>风险提示</h4>
            <p>1. 本产品为非保本浮动收益型产品，不保证本金和收益。</p>
            <p>2. 产品投资范围和比例：本产品将投资于银行存款、债券、货币市场工具等高流动性资产，稳健安全。</p>
            <p>3. 最不利情况：如市场发生极端情况，投资者可能损失部分本金。</p>
            
            <h4>投资者声明</h4>
            <p>1. 本人已阅读并理解本产品的风险提示，了解并愿意承担相关风险。</p>
            <p>2. 本人确认投资资金来源合法，不存在非法集资、洗钱等行为。</p>
            <p>3. 本人同意遵守相关法律法规及本协议的各项规定。</p>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" id="agree-btn">同意并关闭</button>
        </div>
      </div>
    `;
    
    // Append to body
    document.body.appendChild(modal);
    
    // Show modal
    modal.classList.add('show');
    
    // Add event listeners
    document.querySelector('#agreement-modal .modal-close').addEventListener('click', function() {
      closeAgreementModal();
    });
    
    document.getElementById('agree-btn').addEventListener('click', function() {
      document.getElementById('agreement-check').checked = true;
      closeAgreementModal();
    });
    
    function closeAgreementModal() {
      modal.classList.remove('show');
      setTimeout(() => {
        document.body.removeChild(modal);
      }, 300);
    }
  }
  
  /**
   * Confirm purchase
   */
  function confirmPurchase(product, purchaseAmount) {
    // Check if agreement is checked
    if (!document.getElementById('agreement-check').checked) {
      Toast.error('请阅读并同意《理财产品协议》');
      return;
    }
    
    // Check payment password
    const paymentPassword = document.getElementById('payment-password').value;
    if (!paymentPassword) {
      Toast.error('请输入交易密码');
      return;
    }
    
    // Disable button
    const confirmBtn = document.getElementById('confirm-btn');
    confirmBtn.disabled = true;
    confirmBtn.textContent = '处理中...';
    
    // Create purchase request
    const purchaseData = {
      productId: product.id,
      amount: purchaseAmount,
      paymentPassword: paymentPassword
    };
    
    // Call API
    ApiService.post('/api/finance/product/purchase', purchaseData)
      .then(response => {
        if (response.code === 0 && response.data) {
          showSuccess(response.data, product, purchaseAmount);
        } else {
          confirmBtn.disabled = false;
          confirmBtn.textContent = '确认购买';
          Toast.error(response.message || '购买失败，请稍后重试');
        }
      })
      .catch(error => {
        console.error('Error purchasing product:', error);
        confirmBtn.disabled = false;
        confirmBtn.textContent = '确认购买';
        Toast.error('系统错误，请稍后重试');
      });
  }
  
  /**
   * Show success page
   */
  function showSuccess(orderData, product, purchaseAmount) {
    const containerElement = document.getElementById('purchase-content');
    
    // Calculate profit
    const profit = (purchaseAmount * product.expectedReturn * product.duration) / (100 * 365);
    
    // Build HTML
    const html = `
      <div class="purchase-header">
        <div class="purchase-step">
          <div class="step-item completed">
            <div class="step-number">1</div>
            <div class="step-text">选择产品</div>
          </div>
          <div class="step-arrow">
            <i class="fas fa-chevron-right"></i>
          </div>
          <div class="step-item completed">
            <div class="step-number">2</div>
            <div class="step-text">确认信息</div>
          </div>
          <div class="step-arrow">
            <i class="fas fa-chevron-right"></i>
          </div>
          <div class="step-item completed">
            <div class="step-number">3</div>
            <div class="step-text">完成购买</div>
          </div>
        </div>
      </div>
      
      <div class="purchase-result">
        <div class="result-icon success">
          <i class="fas fa-check"></i>
        </div>
        <div class="result-title">购买成功</div>
        <div class="result-message">恭喜您，理财产品购买成功！</div>
        
        <div class="result-details">
          <div class="result-detail">
            <span class="result-label">订单编号：</span>
            <span class="result-value">${orderData.orderNo || '未提供'}</span>
          </div>
          <div class="result-detail">
            <span class="result-label">产品名称：</span>
            <span class="result-value">${product.productName}</span>
          </div>
          <div class="result-detail">
            <span class="result-label">投资金额：</span>
            <span class="result-value">¥${Utils.formatNumber(purchaseAmount)}</span>
          </div>
          <div class="result-detail">
            <span class="result-label">预期收益：</span>
            <span class="result-value">¥${profit.toFixed(2)}</span>
          </div>
          <div class="result-detail">
            <span class="result-label">起息日期：</span>
            <span class="result-value">${Utils.formatDate(new Date(product.valueDate))}</span>
          </div>
          <div class="result-detail">
            <span class="result-label">到期日期：</span>
            <span class="result-value">${Utils.formatDate(new Date(product.dueDate))}</span>
          </div>
        </div>
        
        <div class="result-actions">
          <a href="/financial.html" class="btn btn-outline">
            <i class="fas fa-list"></i> 返回列表
          </a>
          <a href="/index.html" class="btn btn-primary">
            <i class="fas fa-home"></i> 返回首页
          </a>
        </div>
      </div>
    `;
    
    containerElement.innerHTML = html;
  }
  
  /**
   * Show error message
   */
  function showError(message) {
    const containerElement = document.getElementById('purchase-content');
    
    const html = `
      <div class="purchase-result">
        <div class="result-icon error">
          <i class="fas fa-times"></i>
        </div>
        <div class="result-title">操作失败</div>
        <div class="result-message">${message}</div>
        
        <div class="result-actions">
          <a href="/financial.html" class="btn btn-outline">
            <i class="fas fa-list"></i> 返回列表
          </a>
          <button class="btn btn-outline" onclick="history.back()">
            <i class="fas fa-arrow-left"></i> 返回上一页
          </button>
        </div>
      </div>
    `;
    
    containerElement.innerHTML = html;
  }
  
  /**
   * Get risk text
   */
  function getRiskText(riskLevel) {
    switch (riskLevel) {
      case 1: return '低风险';
      case 2: return '中风险';
      case 3: return '高风险';
      default: return '未知风险';
    }
  }
});
